package com.ym.pms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.pms.utils.DescribeCaptchaResult;
import com.ym.pms.utils.JSONResult;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 14:25 2020/12/9
 * @Modified:
 */
@RestController
@CrossOrigin
@Api(tags = "图片验证码票据检验")
public class TCaptchaVerifyController {
    @ApiOperation(value = "图片验证码票据检验")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticket", value = "票据", required = true),
            @ApiImplicitParam(name = "rand", value = "生成的随机数", required = true),
            @ApiImplicitParam(name = "userIp", value = "用户IP", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "验证成功"),
            @ApiResponse(code = 403, message = "验证失败"),
    })
    @PostMapping("verify")
    @CrossOrigin
    public JSONResult verify(@RequestParam String ticket,
                             @RequestParam String rand,
                             @RequestParam String userIp) {
        int res = verifyTicket(ticket, rand, userIp);
        if (res == 1) {
            return JSONResult.ok("验证成功");
        } else {
            return JSONResult.build(403, "验证失败", null);
        }
    }

    private int verifyTicket(String ticket, String rand, String userIp) {
        String res = DescribeCaptchaResult.check(rand, ticket, userIp);
        JSONObject json = JSON.parseObject(res);
        if (json.getInteger("CaptchaCode") == 1) {
            return 1;
        }
        return -1;
    }
}
